import json
import pymysql
from pymysql import OperationalError,IntegrityError,ProgrammingError

config = {
    'host': '127.0.0.1',
    'port': 3306,
    'user': 'root',
    'password': '123456',
    'db': 'py06db',
    'charset': 'utf8'
}


def connect_db():
    try:
        connect = pymysql.connect(**config)
        return connect
    except OperationalError as e:
        # OperationalError 用于捕捉PyMySQL的错误机制，目的是不会出现异常
        print(e)
    except IntegrityError as e:
        print(e)

def write_info(data_list):
    if data_list is None:
        return
    else:
        try:
            connect = connect_db()
            cursor = connect.cursor()
            sql_string = 'insert into films(u_name, u_score, u_types, u_long, u_start_time, u_other_name, u_star, u_director)values(%s, %s, %s,%s, %s, %s,%s, %s)'
            cursor.executemany(sql_string,data_list)
            connect.commit()
            print('写入成功！')
        except ProgrammingError as P:
            print(P)
        except IntegrityError as i:
            print(i)
        finally:
            cursor.close()
            connect.close()
def data_list():
    with open("./in_theaters.json", "r") as f:
        load = json.load(f)
        # print(load)
        ls = []

        for i in load['subjects']:
            name=(i['title'])  # 碟中谍6：全面瓦解
            score = (i['rating']['average']) # 评分8.3
            types=(i['genres'])   # ['动作', '惊悚', '冒险']
            long = (i['durations'])  # ['147分钟', '148分钟(中国大陆)']
            start_time=(i["pubdates"]) #  ['2018-07-27(美国)', '2018-08-31(中国大陆)']
            other_name=(i["original_title"]) # 又名
            for item in i['casts']:
                star =(item["name"])  # 主演
            for item in i['directors']:
                director=(item["name"]) #  导演 克里斯托弗·麦奎里
            ls.append((name, score, ','.join(types),','.join(long),','.join(start_time),other_name,star,director))
        # print(ls)
        return (ls)


def main():
    movie_list = data_list()
    write_info(movie_list)

if __name__ == '__main__':
    main()

